package net.ezsteam.service;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;

import net.ezsteam.cons.EzSteam_Urls;
import net.ezsteam.object.EzSteam_ListItem;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.os.AsyncTask;
import android.util.Log;
import android.widget.Toast;


public class EzSteam_Add_OneCar extends AsyncTask<String, Void, String> {

	private ProgressDialog progdialod;
	private Activity activity;
	private Context context;
	
	private boolean exeption = false;
	
	private String cusID;
	private String year;
	private String make;
	private String model;
	
	// connection establish timeout (timeoutConnection)
	private int timeoutConnection = 5000;
	// socket timeout (timeoutSocket) 
	private int timeoutSocket = 45000;

	JSONArray jArray;
	
	static InputStream is = null;
	static JSONObject jobj = null;
	static String json = ""; 
	List<NameValuePair> params;
	HttpParams httpParameters = new BasicHttpParams();

	
	public EzSteam_Add_OneCar(Activity activity,String cusID,String year,String make,String model) {
		super();
		this.activity = activity;
		this.context = this.activity.getApplicationContext();
		this.cusID = cusID;
		this.year = year;
		this.make = make;
		this.model = model;
		
		Log.d("CustomerID", cusID);
		Log.d("year", year);
	}
	
	
	@Override
	protected void onPreExecute() {
		super.onPreExecute();
		progdialod = ProgressDialog.show(this.activity, "Add Car", "Adding Car, Please Wait",true,false);
	}
	
	
	@Override
	protected String doInBackground(String... urls) {

		try {
			
			HttpConnectionParams.setConnectionTimeout(httpParameters, timeoutConnection);			
			HttpClient httpclient = new DefaultHttpClient(httpParameters);
			
			List<NameValuePair> params = new ArrayList<NameValuePair>();
			params.add(new BasicNameValuePair("customer_id", cusID));
            params.add(new BasicNameValuePair("year", year));
            params.add(new BasicNameValuePair("make", make));
            params.add(new BasicNameValuePair("model", model));

			/*HttpPost httppost = new HttpPost(RegisterUserLink);*/
			HttpPost httppost = new HttpPost(urls[0]);
			JSONObject json = new JSONObject();
			
			json.put("customer_id", cusID);
			json.put("year", year);
			json.put("make", make);
			json.put("model", model);

			JSONArray postjson = new JSONArray();
			postjson.put(json);
			httppost.setHeader("json", json.toString());

			httppost.getParams().setParameter("jsonpost", postjson);
			httppost.setEntity(new UrlEncodedFormEntity(
					params));
			
			HttpResponse httpResponse = httpclient.execute(httppost);
			
			HttpEntity httpEntity = httpResponse.getEntity();
			
			
			Log.e("Add Car Request",postjson.toString());
			
			is = httpEntity.getContent();
			
			}catch (UnsupportedEncodingException e) {
				exeption = true;
				e.printStackTrace();
			}catch (ClientProtocolException e) {
				exeption = true;
				e.printStackTrace();
			} catch (IOException e) {   
				exeption = true;
				e.printStackTrace();
			} catch (JSONException e) {
				exeption = true;
				e.printStackTrace();
			} catch (IllegalStateException e) {
				exeption = true;
				e.printStackTrace();
			} catch (Exception e) {
				exeption = true;
				e.printStackTrace();
			}
			
			try{
				BufferedReader reader=new BufferedReader(new InputStreamReader(is,"iso-8859-1"),8);
				StringBuilder sb=new StringBuilder();
				
				String line=null;
				
				while((line=reader.readLine())!=null){
					//sb.append(line+"n");
					sb.append(line);
				}
				is.close();
				json=sb.toString();
				
				Log.e("JSON RES:",json);
				
			}catch(Exception e){
				exeption = true;
				Log.e("Buffer Error","Error converting result"+e.toString());
			}
		 return json;
		
	}
	
	@Override
	protected void onPostExecute(String result) {

		Log.d("Add Car Responce", result);
		progdialod.dismiss();

			if(!exeption){
				
				try {
					
					JSONArray jarr = new JSONArray(result);
					
					JSONObject jsonobj = jarr.getJSONObject(0);
					
					String state = jsonobj.getString("addcar_state");
					
					if(state.equals("success")){
						int customerid = jsonobj.getInt("car_id");
						
						Toast toast = Toast.makeText(activity, "Car ID : "+customerid, Toast.LENGTH_SHORT);
						toast.show();
					}

					
				} catch (JSONException e) {
					e.printStackTrace();
				}

			
			}else{
				Toast toast = Toast.makeText(activity, "Add Car Failed !!", Toast.LENGTH_SHORT);
				toast.show();
			}
		

		/*Toast toast = Toast.makeText(activity, "UserName Or Password Incorrect. Login Failed !!", Toast.LENGTH_SHORT);
		toast.show();*/
		
		
	}



	
}
